<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Model\AccountSettlement;
use HiCommon\Repository\AccountSettlementOrderRepository;
use HiCommon\Repository\AccountSettlementRepository;
use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\OrderPayRepository;
use HiCommon\Repository\ShopAccountRepository;
use HiCommon\Repository\ShopUserRepository;
use HiCommon\Repository\ViewFinanceCouponRepository;
use HiCommon\Repository\ViewFinanceOrderPayRepository;

class AccountSettleService extends BaseService
{

    /*商户-订单结算信息*/
    public function get_settle_order_info_for_shop($n_shop_id = 0){

        $n_shop_id = intval($n_shop_id);
        if($n_shop_id <= 0){
            return hello_error('查询失败',[],'商户id不能为空');
        }
        $arr_data = [];
        $arr_where = ['shop_id'=>$n_shop_id];

        //不可结算
        $obj_res = ViewFinanceOrderPayRepository::account_settle_can_not($arr_where);
        $n_settle_fee = intval($obj_res->sum('sum_pay_fee')) - intval($obj_res->sum('sum_refund_fee'));
        $arr_data['can_not'] = fee_to_money($n_settle_fee);

        //可结算
        $obj_res = ViewFinanceOrderPayRepository::account_settle_can($arr_where);
        $n_settle_fee = intval($obj_res->sum('sum_pay_fee')) - intval($obj_res->sum('sum_refund_fee'));
        $arr_data['can'] = fee_to_money($n_settle_fee);

        //已结算
        $obj_res = ViewFinanceOrderPayRepository::account_settle_already($arr_where);
        $n_settle_fee = intval($obj_res->sum('sum_pay_fee')) - intval($obj_res->sum('sum_refund_fee'));
        $arr_data['already'] = fee_to_money($n_settle_fee);

        //已结算-打款完成
        $arr_data['already_cashed'] = number_format_money(AccountSettlementRepository::account_order_cash_out_already($n_shop_id));

        //已结算-打款中
        $arr_data['already_cashing'] = number_format_money(AccountSettlementRepository::account_order_cash_out_ing($n_shop_id));

        return  hello_success('成功',$arr_data);
    }

    /*结算列表-商户后台*/
    public function get_settle_order_list_for_shop($arr_input){
        $result = AccountSettlementRepository::settle_order_list_for_shop($arr_input);
        $data = list_page_data($result);

        foreach ($data['data'] as &$value)
        {
            $value['settle_testify_img'] = $value['settle_testify_img']['full_src'];
        }

        return  hello_success('成功',$data);

    }

    /*查询一条结算信息*/
    public function api_find_one($n_id = 0){
        $n_id = intval($n_id);
        if($n_id <= 0){
            return hello_error('数据id不能为空');
        }

        //查询数据
        $result = AccountSettlementRepository::base_find_one($n_id);
        if(is_null($result)){
            $data = [];
        }
        else{
            //json数据转数组
            $data = $result->toarray();

        }
        return  hello_success('成功',$data);

    }

    /*编辑结算信息*/
    public function api_shop_edit_one($arr_input){

        $result = AccountSettlementRepository::base_edit_one($arr_input);
        if($result === false){
            return hello_error('修改失败');
        }

        return  hello_success('修改成功');

    }

    /*提交结算*/
    public function api_submit_settle($n_id){
        $arr_data = [
          'id'=>$n_id,
          'state'=>2,
          'is_refuse'=>2,
          'submit_time'=>time_to_ymdhis(),
        ];
        $result = AccountSettlementRepository::base_edit_one($arr_data);
        if($result === false){
            return hello_error('提交失败');
        }

        return  hello_success('提交成功');
    }

    /*管理后台-订单结算列表*/
    public function get_all_list_for_admin($arr_input){
        $result = AccountSettlementRepository::settle_order_list_for_admin($arr_input);
        $data = list_page_data($result);

        foreach ($data['data'] as &$value)
        {
            $value['settle_testify_img'] = $value['settle_testify_img']['full_src'];
        }
        return  hello_success('成功',$data);

    }

    /*订单结算-驳回结算操作*/
    public function api_refuse_settle($arr_input){
        $n_id = intval($arr_input['id']);
        $s_reason = str_trim($arr_input['reason']);
        if(mb_strlen($s_reason) <= 0){
            return hello_error('请填写驳回原因');
        }

        $arr_data = [
          'id'=>$n_id,
          'state'=>1,
          'is_refuse'=>1,
          'reason'=>$s_reason,
//          'submit_time'=>time_to_ymdhis(),
        ];
        $result = AccountSettlementRepository::base_edit_one($arr_data);
        if($result === false){
            return hello_error('驳回失败');
        }

        return  hello_success('驳回成功');
    }

    /*确认结算*/
    public function api_confirm_settle($n_id){
        $arr_data = [
          'id'=>$n_id,
          'state'=>3,
          'settle_time'=>time_to_ymdhis(),
        ];
        $result = AccountSettlementRepository::base_edit_one($arr_data);
        if($result === false){
            return hello_error('结算失败');
        }

        return  hello_success('结算成功');
    }

    public function api_find_settle($n_shop_id){
        //查询商户资金账户信息
        $result = ShopAccountRepository::base_find_one($n_shop_id);
        if(is_null($result)){
            $arr_data = [];
        }
        else{
            $arr_data = $result->toarray();
        }

        //查询可结算金额
        $result = AccountSettleService::get_settle_order_info_for_shop($n_shop_id);
        if($result['state'] != 0){
            return $result;
        }
        $arr_data['can_settle_money'] = $result['data']['can'];

        return  hello_success('成功',$arr_data);
    }

    /*添加结算-操作*/
    public function api_shop_add_one($arr_input){


        $arr_input['shop_id'] = intval($arr_input['shop_id']);
        if($arr_input['shop_id'] <= 0){
            return hello_error('商户ID不能为空');
        }

        //查询可结算订单
        $arr_where = ['shop_id'=>$arr_input['shop_id']];
        $result = ViewFinanceOrderPayRepository::account_settle_list_can($arr_where);
        $arr_settle_data = $result->toarray();
        $arrIDs = [];
        $arrIDs_data = [];
        foreach ($arr_settle_data as $value) {
            $arrIDs[] = $value['id'];
            $arrIDs_data[] = ['order_pay_id'=>$value['id']];
        }

        //添加主表和附属表
        $n_settle_fee = intval($result->sum('total_fee')) - intval($result->sum('total_refund_fee'));
        $n_settle_money = fee_to_money($n_settle_fee);

        $n_rate = redis_settle_service_fee_rate();
        $n_transfer_account_money = number_format_money($n_settle_money * (1-$n_rate));
        $arr_input['type'] = 'order';//订单结算
        $arr_input['settle_money'] = $n_settle_money;
        $arr_input['service_fee_rate'] = $n_rate;
        $arr_input['transfer_account_money'] = $n_transfer_account_money;
        if($patient = AccountSettlementRepository::base_add_one($arr_input)){
            if ($res = $patient->settle_order()->createMany($arrIDs_data)){

            } else{
                return hello_error('添加失败',[],'添加附属表数据失败');
            }
        }
        else{
            return hello_error('添加失败',[],'添加主表数据失败');
        }

        //修改支付表为已结算
        $arr_wherein = $arrIDs;
        $arr_data = ['is_settle'=>1];
        $result = OrderPayRepository::base_edit_by_wherein($arr_wherein,$arr_data);
        if(!$result){
            return hello_error('添加失败',[],'修改支付表为已结算失败');
        }

        return  hello_success('添加成功');

    }



    /******************************************** 优惠券津贴 ********************************************/


    /*优惠券津贴结算列表-商户后台*/
    public function get_settle_coupon_list_for_shop($arr_input){
        $result = AccountSettlementRepository::settle_coupon_list_for_shop($arr_input);
        $data = list_page_data($result);

        foreach ($data['data'] as &$value)
        {
            $value['settle_testify_img'] = $value['settle_testify_img']['full_src'];
        }

        return  hello_success('成功',$data);

    }

    /*商户-优惠券津贴结算信息*/
    public function get_settle_coupon_info_for_shop($n_shop_id = 0){

        $n_shop_id = intval($n_shop_id);
        if($n_shop_id <= 0){
            return hello_error('查询失败',[],'商户id不能为空');
        }
        $arr_data = [];
        $arr_where = ['shop_id'=>$n_shop_id];

        //不可结算
        $obj_res = ViewFinanceCouponRepository::account_settle_can_not($arr_where);
        $arr_data['can_not'] = number_format_money($obj_res->sum('sum_settle_money'));

        //可结算
        $obj_res = ViewFinanceCouponRepository::account_settle_can($arr_where);
        $arr_data['can'] = number_format_money($obj_res->sum('sum_settle_money'));

        //已结算
        $obj_res = ViewFinanceCouponRepository::account_settle_already($arr_where);
        $arr_data['already'] = number_format_money($obj_res->sum('sum_settle_money'));

        //已结算-打款中
        //已结算-打款完成
        return  hello_success('成功',$arr_data);
    }

    /*商户-查询优惠券津贴结算信息*/
    public function api_find_settle_coupon($n_shop_id){
        //查询商户资金账户信息
        $result = ShopAccountRepository::base_find_one($n_shop_id);
        if(is_null($result)){
            $arr_data = [];
        }
        else{
            $arr_data = $result->toarray();
        }

        //查询可结算金额
        $result = AccountSettleService::get_settle_coupon_info_for_shop($n_shop_id);
        if($result['state'] != 0){
            return $result;
        }
        $arr_data['can_settle_money'] = $result['data']['can'];

        return  hello_success('成功',$arr_data);
    }

    /*商户-查询优惠券津贴结算-添加操作*/
    public function api_shop_settle_coupon_add_one($arr_input){

        $arr_input['shop_id'] = intval($arr_input['shop_id']);
        if($arr_input['shop_id'] <= 0){
            return hello_error('商户ID不能为空');
        }

        //查询可结算订单
        $arr_where = ['shop_id'=>$arr_input['shop_id']];
        $result = ViewFinanceCouponRepository::account_settle_list_can($arr_where);
        $arr_settle_data = $result->toarray();
        $arrIDs = [];
        $arrIDs_data = [];
        foreach ($arr_settle_data as $value) {
            $arrIDs[] = $value['id'];
            $arrIDs_data[] = ['user_coupon_id'=>$value['id']];
        }

        //添加主表和附属表
        $n_settle_money = number_format_money($result->sum('settle_money'));

        $n_rate = redis_settle_service_fee_rate();
        $n_transfer_account_money = number_format_money($n_settle_money * (1-$n_rate));
        $arr_input['type'] = 'coupon';//优惠券津贴结算
        $arr_input['settle_money'] = $n_settle_money;
        $arr_input['service_fee_rate'] = $n_rate;
        $arr_input['transfer_account_money'] = $n_transfer_account_money;
        if($patient = AccountSettlementRepository::base_add_one($arr_input)){
            if ($res = $patient->settle_coupon()->createMany($arrIDs_data)){

            } else{
                return hello_error('添加失败',[],'添加附属表数据失败');
            }
        }
        else{
            return hello_error('添加失败',[],'添加主表数据失败');
        }

        //修改支付表为已结算
        $arr_wherein = $arrIDs;
        $arr_data = ['is_settle'=>1];
        $result = CouponGrantDetailRepository::base_edit_by_wherein($arr_wherein,$arr_data);
        if(!$result){
            return hello_error('添加失败',[],'修改用户优惠券表为已结算失败');
        }

        return  hello_success('添加成功');

    }

    /*管理后台-结算列表*/
    public function get_settle_coupon_list_for_admin($arr_input){
        $result = AccountSettlementRepository::settle_coupon_list_for_admin($arr_input);
        $data = list_page_data($result);

        foreach ($data['data'] as &$value)
        {
            $value['settle_testify_img'] = $value['settle_testify_img']['full_src'];
        }
        return  hello_success('成功',$data);

    }
}